package com.atguigu.educenter.controller;

/**
 * @author shkstart
 * @create 2022-07-24 23:50
 */

import com.atguigu.commonutils.JwtUtils;
import com.atguigu.educenter.entity.UcenterMember;
import com.atguigu.educenter.service.UcenterMemberService;
import com.atguigu.educenter.utils.ConstantWxUtil;
import com.atguigu.educenter.utils.HttpClientUtils;
import com.atguigu.servicebase.exceptionhandler.GuliException;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;

@CrossOrigin
@Controller//注意这里没有配置 @RestController，只是请求地址，不需要返回数据
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService ucenterMemberService;

    //生成微信扫描的二维码
    @GetMapping("login")
    public String getWxCode() {

        //固定地址，后面拼接参数
        /*String url = "https://open.weixin.qq.com/" +
                "connect/qrconnect?appId=" + ConstantWxUtil.WX_OPEN_APP_ID + "response_type=code" +*/
        //请求微信地址就可以了
        // 微信开放平台授权baseUrl %s相当于?，代表占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +//1.appid：应用唯一标识
                "&redirect_uri=%s" +//2.redirect_uri：使用urlEncode对链接进行处理
                "&response_type=code" +//3.response_type：填code
                "&scope=snsapi_login" +//4.scope：应用授权作用域，拥有多个作用域用逗号（,）分隔
                "&state=%s" +//5.state：用于保持请求和回调的状态，授权请求后原样带回给第三方。
                "#wechat_redirect";

        // 对redirect_uri进行urlEncode编码
        String redirectUrl = ConstantWxUtil.WX_OPEN_REDIRECT_URL; //获取业务服务器重定向地址
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8"); //url编码
        } catch (Exception e) {
            throw new GuliException(20001,e.getMessage());
        }

        // 防止csrf攻击（跨站请求伪造攻击）
        //String state = UUID.randomUUID().toString().replaceAll("-", "");//一般情况下会使用一个随机数
        //state="atguigu"

        //设置%s里面的值
        String url = String.format(
                baseUrl,//要拼的参数
                ConstantWxUtil.WX_OPEN_APP_ID,//第一个百分号
                redirectUrl,//第二个百分号
                "atguigu"//第三个百分号
        );
        //重定向到请求微信地址里面
        return "redirect:" + url;

    }

    //获取扫描人信息，添加数据，扫完码转到这里来
    @GetMapping("callback")
    public String callback(String code,String state) {
        System.out.println("code:"+code);
        System.out.println("state:"+state);
        //---------------------------------------------------------
        try {
        //1.获取code值，临时票据，类似于验证码
        // 2.拿着code请求微信固定的地址，得到两个值：access_token 和 openid
        String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=%s" +//appid
                "&secret=%s" +//密钥
                "&code=%s" +//code值
                "&grant_type=authorization_code";
        //拼接三个参数：id，密钥，code值
        //设置%s里面的值
        String accessTokenUrl = String.format(
                baseAccessTokenUrl,//要拼的参数
                ConstantWxUtil.WX_OPEN_APP_ID,//第一个百分号
                ConstantWxUtil.WX_OPEN_APP_SECRET,//第二个百分号
                code//第三个百分号
        );
        //3.请求这个拼接好的地址，得到返回两个值：access_token 和 openid
        //使用httpclient发送请求，得到返回结果
            String accessTokenInfo = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessTokenInfo"+accessTokenInfo);
            //4.从accessTokenInfo字符串中取出两个值：access_token 和 openid
            //把accessTokenInfo字符串转换成map集合，根据map里面的key取出值
            //要用到工具gson
            Gson gson = new Gson();
            HashMap mapAccessToken = gson.fromJson(accessTokenInfo, HashMap.class);
            //取值
            String accesstoken = (String)mapAccessToken.get("access_token");
            String openid = (String)mapAccessToken.get("openid");
            /*//5.拿着得到的access_token 和 openid，再去请求微信提供的固定地址，获取到扫描人信息
            //访问微信的资源服务器，获取用户信息
            String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
            "?access_token=%s" +
            "&openid=%s";
            //设置%s里面的值
            String userInfoUrl = String.format(
                    baseUserInfoUrl,//要拼的参数
                    access_token,//第一个百分号
                    openid);//第二个百分号
            //发送请求
            String userInfo = HttpClientUtils.get(userInfoUrl);
            System.out.println("userInfo:"+userInfo);
            //获取返回userInfo字符串扫描人信息
            Gson gson2 = new Gson();
            HashMap userInfoMap = gson2.fromJson(userInfo, HashMap.class);
            String nickname = (String) userInfoMap.get("nickname");
            String headimgurl = (String) userInfoMap.get("headimgurl");*/

            //6.把扫描人信息添加到数据库（注册）
            UcenterMember menber= ucenterMemberService.getOpenIdMenber(openid);
            if (menber == null) {

                //5.拿着得到的access_token 和 openid，再去请求微信提供的固定地址，获取到扫描人信息
                //访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                //设置%s里面的值
                String userInfoUrl = String.format(
                        baseUserInfoUrl,//要拼的参数
                        accesstoken,//第一个百分号
                        openid);//第二个百分号
                //发送请求
                String userInfo = HttpClientUtils.get(userInfoUrl);
                System.out.println("userInfo:"+userInfo);
                //获取返回userInfo字符串扫描人信息
               // Gson gson2 = new Gson();
                HashMap<String, Object> userInfoMap = gson.fromJson(userInfo, HashMap.class);
                String nickname = (String) userInfoMap.get("nickname");//昵称
                String headimgurl = (String) userInfoMap.get("headimgurl");//头像
                System.out.println("1.nickname:"+nickname);
                System.out.println("2.headimgurl:"+headimgurl);
                //---------------------------------------------

                UcenterMember member = new UcenterMember();
                System.out.println("3.1.end");
                member.setOpenid(openid);
                System.out.println("3.2.end");
                member.setNickname(nickname);
                System.out.println("3.3.end");
                member.setAvatar(headimgurl);
                System.out.println("3.4.end");
                ucenterMemberService.save(member);
                //baseMapper.insert(member);
                System.out.println("3.5.end");
            }

            //--------------整合JWT令牌--------------
            System.out.println("menber.getId():"+menber.getId());
            System.out.println("menber.getNickname():"+menber.getNickname());
            String jwtToken = JwtUtils.getJwtToken(menber.getId(),menber.getNickname());
            //7.最后,//因为端口号不同存在蛞蝓问题，cookie不能跨域，所以这里使用url重写
            return "redirect:http://localhost:3000?token=" + jwtToken;
        } catch (Exception e) {
            throw new GuliException(20001,"登录失败,整合JWT令牌");
        }
    }
    //accessTokenInfo
    // {"access_token":"59_usJQsbpUJObFLovLKvyRDqPJayj3EJ16UEOdYaG__AZV8pJQ4KVQk4U_-oGK2VuB43aw0tcEQpX7MaH2MOpSg9uvprhcB4m6p7BVPvE97AE",
    // "expires_in":7200,
    // "refresh_token":"59_m7nz7GinYf9rL6MxLb0S1n3wg9wpliplGbz0IbuAUxne7N9-ZUifMS8QXhRX6pkqAk_xSXwCvtGH5whTucCW8anqMaQpNyjtMbt7NrVvB4Q",
    // "openid":"o3_SC5zjNkh6iigc-t2gp6b9xlNQ",
    // "scope":"snsapi_login",
    // "unionid":"oWgGz1PjiUqAsEZdsxeonAtf5TzM"}

    //userInfo:
    // {"openid":"o3_SC5zjNkh6iigc-t2gp6b9xlNQ",
    // "nickname":"圆溜溜",
    // "sex":0,
    // "language":"",
    // "city":"","province":"",
    // "country":"",
    // "headimgurl":"https:\/\/thirdwx.qlogo.cn\/mmopen\/vi_32\/muG6Vaz8fm2WT2ibQYkIl79ljiciaia91TuLKoaw13ZHGgEO6WXkBKCe6ib5bOFpmjvP2Ay7Krf0xwfZdB0IIgNDe7w\/132",
    // "privilege":[],
    // "unionid":"oWgGz1PjiUqAsEZdsxeonAtf5TzM"}
}
